package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.NursingElderMapper;
import com.zzyl.mapper.SysUserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class AlertRuleServiceImpl implements AlertRuleService {
    private static final Logger log = LoggerFactory.getLogger(AlertRuleServiceImpl.class);
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private NursingElderMapper nursingElderMapper;

    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 新增报警规则
     *
     * @param dto
     */
    @Override
    public void add(AlertRuleDto dto) {
        AlertRule alertRule = BeanUtil.copyProperties(dto, AlertRule.class);
        alertRuleMapper.add(alertRule);
    }

    /**
     * 分页获取告警规则列表
     *
     * @param pageNum
     * @param pageSize
     * @param alertRuleName
     * @param functionName
     * @param productKey
     * @return
     */
    @Override
    public PageResponse<AlertRuleVo> findPageList(Integer pageNum, Integer pageSize, String alertRuleName, String functionName, String productKey) {
        PageHelper.startPage(pageNum, pageSize);

        Page<AlertRuleVo> page = alertRuleMapper.findPageList(alertRuleName, functionName, productKey);
        page.getResult().forEach(vo -> {
            vo.setRules(vo.getFunctionName() + vo.getOperator() + vo.getValue() + ", 持续" + vo.getDuration() + "个周期就报警");
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 获取单个告警规则
     *
     * @param id
     * @return
     */
    @Override
    public AlertRuleVo findById(Integer id) {
        return alertRuleMapper.findById(id);
    }

    /**
     * 更新告警规则
     *
     * @param dto
     */
    @Override
    public void updateRule(AlertRuleDto dto) {
        AlertRule alertRule = BeanUtil.copyProperties(dto, AlertRule.class);
        alertRuleMapper.updateRule(alertRule);
    }

    /**
     * 删除告警规则
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        alertRuleMapper.deleteById(id);
    }

    /**
     * 启用-禁用
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Integer id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    /**
     * 报警规则校验
     *
     * @param vo
     */
    @Override
    public void alertFilter(DeviceDataVo vo) {
        //1. 判断当前的数据是否是积压的数据(判断设备的汇报时间和当前时间的差值是否超过60秒)
        LocalDateTime alarmTime = vo.getAlarmTime();
        LocalDateTime now = LocalDateTime.now();
        long between = LocalDateTimeUtil.between(alarmTime, now, ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }

        //2. 查询当前产品针对当前规格的规则
        List<AlertRuleVo> productRules = alertRuleMapper.queryAlertRule(vo.getFunctionId(), null, vo.getProductKey());

        //3. 查询针对当前设备的当前规格的规则
        List<AlertRuleVo> deviceRules = alertRuleMapper.queryAlertRule(vo.getFunctionId(), vo.getIotId(), vo.getProductKey());

        //4. 合并产品的规则和设备单独配置的规则
        List<AlertRuleVo> alertRules = new ArrayList<>();
        alertRules.addAll(productRules);
        alertRules.addAll(deviceRules);

        //规则去重
        alertRules = alertRules.stream().distinct().collect(Collectors.toList());

        if (alertRules.size() <= 0) {
            return;
        }

        //5. 遍历每一个规则, 然后用当前的规则校验数据是否合规
        alertRules.stream().forEach(ruleVo -> {
            deviceDataAlertHandler(ruleVo, vo);
        });

    }

    /**
     * 检验数据是否合规
     *
     * @param ruleVo
     * @param vo
     */
    private void deviceDataAlertHandler(AlertRuleVo ruleVo, DeviceDataVo vo) {
        //1. 获取规则中的生效时间段
        String alertEffectivePeriod = ruleVo.getAlertEffectivePeriod();
        String[] strs = alertEffectivePeriod.split("~");
        LocalTime startTime = LocalTime.parse(strs[0]);
        LocalTime endTime = LocalTime.parse(strs[1]);

        //2. 当前数据的汇报时间是否在生效时间段内, 如果不在则结束
        LocalTime time = vo.getAlarmTime().toLocalTime();
        if (startTime.isAfter(time) || endTime.isBefore(time)) {
            return;
        }

        String countKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + vo.getIotId() + ":" + vo.getFunctionId() + ":" + vo.getProductKey();
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + vo.getIotId() + ":" + vo.getFunctionId() + ":" + vo.getProductKey();

        //3. 如果在则判断数据是否达到了规则要求的阈值
        //x==y返回0, x<y返回小于0的数, x>y返回大于0的数
        int result = NumberUtil.compare(ruleVo.getValue(), Float.parseFloat(vo.getDataValue()));
        if ((">=".equals(ruleVo.getOperator()) && result >= 0) || ("<".equals(ruleVo.getOperator()) && result < 0)) {
            log.info("老人的健康数据正常");
            //删除redis的统计数据, 然后让redis重新统计连续的三次
            //key的构建: 前缀+设备+维度+产品id
            //4. 如果达到了阈值则删除redis的统计数据
            redisTemplate.delete(countKey);
            return;
        }

        log.info("老人的数据异常, {}, 具体的值: {}, 标准值: {}", vo.getFunctionId(), vo.getDataValue(), ruleVo.getValue());
        String silentValue = redisTemplate.opsForValue().get(silentKey);
        if (ObjectUtil.isNotEmpty(silentValue)) {
            //前面5分钟之内已经通知过了护工, 维修人员, 超级管理员
            return;
        }

        //4. 如果达到了阈值则删除redis的统计数量
        String _count = redisTemplate.opsForValue().get(countKey);
        int count = ObjectUtil.isEmpty(_count) ? 0 : Integer.parseInt(_count);

        //5. 次数加一
        count += 1;

        //6. 判断连续的次数是否达到了规则中的次数要求, 如果达到了就触发预警, 如果没有打到把当前统计的次数写入redis
        if (count < ruleVo.getDuration()) {
            //如果没有达到把当前统计的次数写入redis
            redisTemplate.opsForValue().set(countKey, count + "");
            return;
        }

        //7. 如果达到了就触发预警
        //7.1 删除redis中统计的次数, 让数据重新从0开始统计
        redisTemplate.delete(countKey);

        //7.2 添加一个key-value作为沉默周期(过期时间)
        redisTemplate.opsForValue().set(silentKey, "1", ruleVo.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //添加报警数据
        //8.1 判断当前的数据是针对老人的数据还是针对设备的数据
        List<Long> ids = new ArrayList<>();
        if (ruleVo.getAlertDataType() == 1) {
            //8.2 如果是针对设备的, 那么就查询所有的维修人员
            ids = sysUserRoleMapper.selectUserIdsByRole("维修工");
        } else if (ruleVo.getAlertDataType() == 0){
            //8.3 如果是针对老人的, 还需要继续判断, 当前数据是固定设备还是随身设备
            if (vo.getLocationType().toString().equals(SuperConstant.DATA_STATE_0)) {
                //随身设备
                ids = nursingElderMapper.selectNursingIdsByIotid(vo.getIotId());
            } else {
                //固定设备
                ids = nursingElderMapper.selectNursingIdsByIotidWithBed(vo.getIotId());
            }
        }

        //8.4 查询所有的超级管理员
        List<Long> superManagementIds = sysUserRoleMapper.selectUserIdsByRole("超级管理员");
        ids.addAll(superManagementIds);

        //8.5 批量插入报警数据(一个人插入一行数据)
        List<AlertData> list = insertAlertData(vo, ruleVo, ids);

        //获取需要推送的用户id列表
        List<Long> userIds = list.stream().map(AlertData::getUserId).collect(Collectors.toList());

        //发送websocket消息
        websocketNotify(ruleVo, list.get(0), userIds);

    }



    /**
     * 发送websocket通知
     *
     * @param alertRuleVo 报警规则
     * @param alertData 报警数据
     */
    private void websocketNotify(AlertRuleVo alertRuleVo, AlertData alertData, List<Long> userIds) {
        // websocket通知：弹窗消息
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRuleVo.getFunctionName());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);
        //给指定消费者发送消息
        webSocketServer.sendMessageToConsumer(alertNotifyDto, userIds);
    }


    /**
     * 新增报警数据
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRuleVo  报警规则
     * @param consumerIds  消费者id列表
     * @return 报警数据
     */
    private List<AlertData> insertAlertData(DeviceDataVo deviceDataVo, AlertRuleVo alertRuleVo, List<Long> consumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRuleVo.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRuleVo.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = consumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.batchInsert(list);
        return list;
    }
}